home *** CD-ROM | disk | FTP | other *** search
/ IRIX Base Documentation 1998 November / IRIX 6.5.2 Base Documentation November 1998.img / usr / share / catman / u_man / cat1 / perlfaq4.z / perlfaq4
Text File  |  1998-10-30  |  64KB  |  1,519 lines

  1.  
  2.  
  3.  
  4. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  5.  
  6.  
  7.  
  8. NNNNAAAAMMMMEEEE
  9.      perlfaq4 - Data Manipulation ($Revision: 1.19 $, $Date: 1997/04/24
  10.      22:43:57 $)
  11.  
  12. DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  13.      The section of the FAQ answers question related to the manipulation of
  14.      data as numbers, dates, strings, arrays, hashes, and miscellaneous data
  15.      issues.
  16.  
  17. DDDDaaaattttaaaa:::: NNNNuuuummmmbbbbeeeerrrrssss
  18.      WWWWhhhhyyyy aaaammmm IIII ggggeeeettttttttiiiinnnngggg lllloooonnnngggg ddddeeeecccciiiimmmmaaaallllssss ((((eeeegggg,,,, 11119999....9999444499999999999999999999999999999999999999999999)))) iiiinnnnsssstttteeeeaaaadddd ooooffff tttthhhheeee
  19.      nnnnuuuummmmbbbbeeeerrrrssss IIII sssshhhhoooouuuulllldddd bbbbeeee ggggeeeettttttttiiiinnnngggg ((((eeeegggg,,,, 11119999....99995555))))????
  20.  
  21.      Internally, your computer represents floating-point numbers in binary.
  22.      Floating-point numbers read in from a file, or appearing as literals in
  23.      your program, are converted from their decimal floating-point
  24.      representation (eg, 19.95) to the internal binary representation.
  25.  
  26.      However, 19.95 can't be precisely represented as a binary floating-point
  27.      number, just like 1/3 can't be exactly represented as a decimal
  28.      floating-point number.  The computer's binary representation of 19.95,
  29.      therefore, isn't exactly 19.95.
  30.  
  31.      When a floating-point number gets printed, the binary floating-point
  32.      representation is converted back to decimal.  These decimal numbers are
  33.      displayed in either the format you specify with _p_r_i_n_t_f(), or the current
  34.      output format for numbers (see the section on $# in the _p_e_r_l_v_a_r manpage
  35.      if you use print.  $# has a different default value in Perl5 than it did
  36.      in Perl4.  Changing $# yourself is deprecated.
  37.  
  38.      This affects aaaallllllll computer languages that represent decimal floating-point
  39.      numbers in binary, not just Perl.  Perl provides arbitrary-precision
  40.      decimal numbers with the Math::BigFloat module (part of the standard Perl
  41.      distribution), but mathematical operations are consequently slower.
  42.  
  43.      To get rid of the superfluous digits, just use a format (eg,
  44.      printf("%.2f", 19.95)) to get the required precision.
  45.  
  46.      WWWWhhhhyyyy iiiissssnnnn''''tttt mmmmyyyy ooooccccttttaaaallll ddddaaaattttaaaa iiiinnnntttteeeerrrrpppprrrreeeetttteeeedddd ccccoooorrrrrrrreeeeccccttttllllyyyy????
  47.  
  48.      Perl only understands octal and hex numbers as such when they occur as
  49.      literals in your program.  If they are read in from somewhere and
  50.      assigned, no automatic conversion takes place.  You must explicitly use
  51.      _o_c_t() or _h_e_x() if you want the values converted.  _o_c_t() interprets both
  52.      hex ("0x350") numbers and octal ones ("0350" or even without the leading
  53.      "0", like "377"), while _h_e_x() only converts hexadecimal ones, with or
  54.      without a leading "0x", like "0x255", "3A", "ff", or "deadbeef".
  55.  
  56.      This problem shows up most often when people try using _c_h_m_o_d(), _m_k_d_i_r(),
  57.      _u_m_a_s_k(), or _s_y_s_o_p_e_n(), which all want permissions in octal.
  58.  
  59.  
  60.  
  61.  
  62.  
  63.                                                                         PPPPaaaaggggeeee 1111
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  71.  
  72.  
  73.  
  74.          chmod(644,  $file); # WRONG -- perl -w catches this
  75.          chmod(0644, $file); # right
  76.  
  77.  
  78.      DDDDooooeeeessss ppppeeeerrrrllll hhhhaaaavvvveeee aaaa rrrroooouuuunnnndddd ffffuuuunnnnccccttttiiiioooonnnn????  WWWWhhhhaaaatttt aaaabbbboooouuuutttt _c_e_i_l() and _f_l_o_o_r()? Trig
  79.      functions?
  80.  
  81.      For rounding to a certain number of digits, _s_p_r_i_n_t_f() or _p_r_i_n_t_f() is
  82.      usually the easiest route.
  83.  
  84.      The POSIX module (part of the standard perl distribution) implements
  85.      _c_e_i_l(), _f_l_o_o_r(), and a number of other mathematical and trigonometric
  86.      functions.
  87.  
  88.      In 5.000 to 5.003 Perls, trigonometry was done in the Math::Complex
  89.      module.  With 5.004, the Math::Trig module (part of the standard perl
  90.      distribution) implements the trigonometric functions. Internally it uses
  91.      the Math::Complex module and some functions can break out from the real
  92.      axis into the complex plane, for example the inverse sine of 2.
  93.  
  94.      Rounding in financial applications can have serious implications, and the
  95.      rounding method used should be specified precisely.  In these cases, it
  96.      probably pays not to trust whichever system rounding is being used by
  97.      Perl, but to instead implement the rounding function you need yourself.
  98.  
  99.      HHHHoooowwww ddddoooo IIII ccccoooonnnnvvvveeeerrrrtttt bbbbiiiittttssss iiiinnnnttttoooo iiiinnnnttttssss????
  100.  
  101.      To turn a string of 1s and 0s like '10110110' into a scalar containing
  102.      its binary value, use the _p_a_c_k() function (documented in the section on
  103.      _p_a_c_k in the _p_e_r_l_f_u_n_c manpage):
  104.  
  105.          $decimal = pack('B8', '10110110');
  106.  
  107.      Here's an example of going the other way:
  108.  
  109.          $binary_string = join('', unpack('B*', "\x29"));
  110.  
  111.  
  112.      HHHHoooowwww ddddoooo IIII mmmmuuuullllttttiiiippppllllyyyy mmmmaaaattttrrrriiiicccceeeessss????
  113.  
  114.      Use the Math::Matrix or Math::MatrixReal modules (available from CPAN) or
  115.      the PDL extension (also available from CPAN).
  116.  
  117.      HHHHoooowwww ddddoooo IIII ppppeeeerrrrffffoooorrrrmmmm aaaannnn ooooppppeeeerrrraaaattttiiiioooonnnn oooonnnn aaaa sssseeeerrrriiiieeeessss ooooffff iiiinnnntttteeeeggggeeeerrrrssss????
  118.  
  119.      To call a function on each element in an array, and collect the results,
  120.      use:
  121.  
  122.          @results = map { my_func($_) } @array;
  123.  
  124.      For example:
  125.  
  126.  
  127.  
  128.  
  129.                                                                         PPPPaaaaggggeeee 2222
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  137.  
  138.  
  139.  
  140.          @triple = map { 3 * $_ } @single;
  141.  
  142.      To call a function on each element of an array, but ignore the results:
  143.  
  144.          foreach $iterator (@array) {
  145.              &my_func($iterator);
  146.          }
  147.  
  148.      To call a function on each integer in a (small) range, you ccccaaaannnn use:
  149.  
  150.          @results = map { &my_func($_) } (5 .. 25);
  151.  
  152.      but you should be aware that the .. operator creates an array of all
  153.      integers in the range.  This can take a lot of memory for large ranges.
  154.      Instead use:
  155.  
  156.          @results = ();
  157.          for ($i=5; $i < 500_005; $i++) {
  158.              push(@results, &my_func($i));
  159.          }
  160.  
  161.  
  162.      HHHHoooowwww ccccaaaannnn IIII oooouuuuttttppppuuuutttt RRRRoooommmmaaaannnn nnnnuuuummmmeeeerrrraaaallllssss????
  163.  
  164.      Get the http://www.perl.com/CPAN/modules/by-module/Roman module.
  165.  
  166.      WWWWhhhhyyyy aaaarrrreeeennnn''''tttt mmmmyyyy rrrraaaannnnddddoooommmm nnnnuuuummmmbbbbeeeerrrrssss rrrraaaannnnddddoooommmm????
  167.  
  168.      The short explanation is that you're getting pseudorandom numbers, not
  169.      random ones, because that's how these things work.  A longer explanation
  170.      is available on http://www.perl.com/CPAN/doc/FMTEYEWTK/random, courtesy
  171.      of Tom Phoenix.
  172.  
  173.      You should also check out the Math::TrulyRandom module from CPAN.
  174.  
  175. DDDDaaaattttaaaa:::: DDDDaaaatttteeeessss
  176.      HHHHoooowwww ddddoooo IIII ffffiiiinnnndddd tttthhhheeee wwwweeeeeeeekkkk----ooooffff----tttthhhheeee----yyyyeeeeaaaarrrr////ddddaaaayyyy----ooooffff----tttthhhheeee----yyyyeeeeaaaarrrr????
  177.  
  178.      The day of the year is in the array returned by _l_o_c_a_l_t_i_m_e() (see the
  179.      section on _l_o_c_a_l_t_i_m_e in the _p_e_r_l_f_u_n_c manpage):
  180.  
  181.          $day_of_year = (localtime(time()))[7];
  182.  
  183.      or more legibly (in 5.004 or higher):
  184.  
  185.          use Time::localtime;
  186.          $day_of_year = localtime(time())->yday;
  187.  
  188.      You can find the week of the year by dividing this by 7:
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195.                                                                         PPPPaaaaggggeeee 3333
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  203.  
  204.  
  205.  
  206.          $week_of_year = int($day_of_year / 7);
  207.  
  208.      Of course, this believes that weeks start at zero.
  209.  
  210.      HHHHoooowwww ccccaaaannnn IIII ccccoooommmmppppaaaarrrreeee ttttwwwwoooo ddddaaaatttteeee ssssttttrrrriiiinnnnggggssss????
  211.  
  212.      Use the Date::Manip or Date::DateCalc modules from CPAN.
  213.  
  214.      HHHHoooowwww ccccaaaannnn IIII ttttaaaakkkkeeee aaaa ssssttttrrrriiiinnnngggg aaaannnndddd ttttuuuurrrrnnnn iiiitttt iiiinnnnttttoooo eeeeppppoooocccchhhh sssseeeeccccoooonnnnddddssss????
  215.  
  216.      If it's a regular enough string that it always has the same format, you
  217.      can split it up and pass the parts to timelocal in the standard
  218.      Time::Local module.  Otherwise, you should look into one of the Date
  219.      modules from CPAN.
  220.  
  221.      HHHHoooowwww ccccaaaannnn IIII ffffiiiinnnndddd tttthhhheeee JJJJuuuulllliiiiaaaannnn DDDDaaaayyyy????
  222.  
  223.      Neither Date::Manip nor Date::DateCalc deal with Julian days.  Instead,
  224.      there is an example of Julian date calculation in
  225.      http://www.perl.com/CPAN/authors/David_Muir_Sharnoff/modules/Time/JulianDay.pm.gz,
  226.      which should help.
  227.  
  228.      DDDDooooeeeessss PPPPeeeerrrrllll hhhhaaaavvvveeee aaaa yyyyeeeeaaaarrrr 2222000000000000 pppprrrroooobbbblllleeeemmmm????
  229.  
  230.      Not unless you use Perl to create one. The date and time functions
  231.      supplied with perl (gmtime and localtime) supply adequate information to
  232.      determine the year well beyond 2000 (2038 is when trouble strikes).  The
  233.      year returned by these functions when used in an array context is the
  234.      year minus 1900. For years between 1910 and 1999 this _h_a_p_p_e_n_s to be a 2-
  235.      digit decimal number. To avoid the year 2000 problem simply do not treat
  236.      the year as a 2-digit number.  It isn't.
  237.  
  238.      When _g_m_t_i_m_e() and _l_o_c_a_l_t_i_m_e() are used in a scalar context they return a
  239.      timestamp string that contains a fully-expanded year.  For example,
  240.      $timestamp = gmtime(1005613200) sets $timestamp to "Tue Nov 13 01:00:00
  241.      2001".  There's no year 2000 problem here.
  242.  
  243. DDDDaaaattttaaaa:::: SSSSttttrrrriiiinnnnggggssss
  244.      HHHHoooowwww ddddoooo IIII vvvvaaaalllliiiiddddaaaatttteeee iiiinnnnppppuuuutttt????
  245.  
  246.      The answer to this question is usually a regular expression, perhaps with
  247.      auxiliary logic.  See the more specific questions (numbers, email
  248.      addresses, etc.) for details.
  249.  
  250.      HHHHoooowwww ddddoooo IIII uuuunnnneeeessssccccaaaappppeeee aaaa ssssttttrrrriiiinnnngggg????
  251.  
  252.      It depends just what you mean by "escape".  URL escapes are dealt with in
  253.      the _p_e_r_l_f_a_q_9 manpage.  Shell escapes with the backslash (\) character are
  254.      removed with:
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261.                                                                         PPPPaaaaggggeeee 4444
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  269.  
  270.  
  271.  
  272.          s/\\(.)/$1/g;
  273.  
  274.      Note that this won't expand \n or \t or any other special escapes.
  275.  
  276.      HHHHoooowwww ddddoooo IIII rrrreeeemmmmoooovvvveeee ccccoooonnnnsssseeeeccccuuuuttttiiiivvvveeee ppppaaaaiiiirrrrssss ooooffff cccchhhhaaaarrrraaaacccctttteeeerrrrssss????
  277.  
  278.      To turn "abbcccd" into "abccd":
  279.  
  280.          s/(.)\1/$1/g;
  281.  
  282.  
  283.      HHHHoooowwww ddddoooo IIII eeeexxxxppppaaaannnndddd ffffuuuunnnnccccttttiiiioooonnnn ccccaaaallllllllssss iiiinnnn aaaa ssssttttrrrriiiinnnngggg????
  284.  
  285.      This is documented in the _p_e_r_l_r_e_f manpage.  In general, this is fraught
  286.      with quoting and readability problems, but it is possible.  To
  287.      interpolate a subroutine call (in a list context) into a string:
  288.  
  289.          print "My sub returned @{[mysub(1,2,3)]} that time.\n";
  290.  
  291.      If you prefer scalar context, similar chicanery is also useful for
  292.      arbitrary expressions:
  293.  
  294.          print "That yields ${\($n + 5)} widgets\n";
  295.  
  296.      See also "How can I expand variables in text strings?" in this section of
  297.      the FAQ.
  298.  
  299.      HHHHoooowwww ddddoooo IIII ffffiiiinnnndddd mmmmaaaattttcccchhhhiiiinnnngggg////nnnneeeessssttttiiiinnnngggg aaaannnnyyyytttthhhhiiiinnnngggg????
  300.  
  301.      This isn't something that can be tackled in one regular expression, no
  302.      matter how complicated.  To find something between two single characters,
  303.      a pattern like /x([^x]*)x/ will get the intervening bits in $1. For
  304.      multiple ones, then something more like /alpha(.*?)omega/ would be
  305.      needed.  But none of these deals with nested patterns, nor can they.  For
  306.      that you'll have to write a parser.
  307.  
  308.      HHHHoooowwww ddddoooo IIII rrrreeeevvvveeeerrrrsssseeee aaaa ssssttttrrrriiiinnnngggg????
  309.  
  310.      Use _r_e_v_e_r_s_e() in a scalar context, as documented in the reverse entry in
  311.      the _p_e_r_l_f_u_n_c manpage.
  312.  
  313.          $reversed = reverse $string;
  314.  
  315.  
  316.      HHHHoooowwww ddddoooo IIII eeeexxxxppppaaaannnndddd ttttaaaabbbbssss iiiinnnn aaaa ssssttttrrrriiiinnnngggg????
  317.  
  318.      You can do it the old-fashioned way:
  319.  
  320.          1 while $string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
  321.  
  322.      Or you can just use the Text::Tabs module (part of the standard perl
  323.      distribution).
  324.  
  325.  
  326.  
  327.                                                                         PPPPaaaaggggeeee 5555
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  335.  
  336.  
  337.  
  338.          use Text::Tabs;
  339.          @expanded_lines = expand(@lines_with_tabs);
  340.  
  341.  
  342.      HHHHoooowwww ddddoooo IIII rrrreeeeffffoooorrrrmmmmaaaatttt aaaa ppppaaaarrrraaaaggggrrrraaaapppphhhh????
  343.  
  344.      Use Text::Wrap (part of the standard perl distribution):
  345.  
  346.          use Text::Wrap;
  347.          print wrap("\t", '  ', @paragraphs);
  348.  
  349.      The paragraphs you give to Text::Wrap may not contain embedded newlines.
  350.      Text::Wrap doesn't justify the lines (flush-right).
  351.  
  352.      HHHHoooowwww ccccaaaannnn IIII aaaacccccccceeeessssssss////cccchhhhaaaannnnggggeeee tttthhhheeee ffffiiiirrrrsssstttt NNNN lllleeeetttttttteeeerrrrssss ooooffff aaaa ssssttttrrrriiiinnnngggg????
  353.  
  354.      There are many ways.  If you just want to grab a copy, use substr:
  355.  
  356.          $first_byte = substr($a, 0, 1);
  357.  
  358.      If you want to modify part of a string, the simplest way is often to use
  359.      _s_u_b_s_t_r() as an lvalue:
  360.  
  361.          substr($a, 0, 3) = "Tom";
  362.  
  363.      Although those with a regexp kind of thought process will likely prefer
  364.  
  365.          $a =~ s/^.../Tom/;
  366.  
  367.  
  368.      HHHHoooowwww ddddoooo IIII cccchhhhaaaannnnggggeeee tttthhhheeee NNNNtttthhhh ooooccccccccuuuurrrrrrrreeeennnncccceeee ooooffff ssssoooommmmeeeetttthhhhiiiinnnngggg????
  369.  
  370.      You have to keep track.  For example, let's say you want to change the
  371.      fifth occurrence of "whoever" or "whomever" into "whosoever" or
  372.      "whomsoever", case insensitively.
  373.  
  374.          $count = 0;
  375.          s{((whom?)ever)}{
  376.              ++$count == 5           # is it the 5th?
  377.                  ? "${2}soever"      # yes, swap
  378.                  : $1                # renege and leave it there
  379.          }igex;
  380.  
  381.  
  382.      HHHHoooowwww ccccaaaannnn IIII ccccoooouuuunnnntttt tttthhhheeee nnnnuuuummmmbbbbeeeerrrr ooooffff ooooccccccccuuuurrrrrrrreeeennnncccceeeessss ooooffff aaaa ssssuuuubbbbssssttttrrrriiiinnnngggg wwwwiiiitttthhhhiiiinnnn aaaa ssssttttrrrriiiinnnngggg????
  383.  
  384.      There are a number of ways, with varying efficiency: If you want a count
  385.      of a certain single character (X) within a string, you can use the tr///
  386.      function like so:
  387.  
  388.  
  389.  
  390.  
  391.  
  392.  
  393.                                                                         PPPPaaaaggggeeee 6666
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  401.  
  402.  
  403.  
  404.          $string = "ThisXlineXhasXsomeXx'sXinXit":
  405.          $count = ($string =~ tr/X//);
  406.          print "There are $count X charcters in the string";
  407.  
  408.      This is fine if you are just looking for a single character.  However, if
  409.      you are trying to count multiple character substrings within a larger
  410.      string, tr/// won't work.  What you can do is wrap a _w_h_i_l_e() loop around
  411.      a global pattern match.  For example, let's count negative integers:
  412.  
  413.          $string = "-9 55 48 -2 23 -76 4 14 -44";
  414.          while ($string =~ /-\d+/g) { $count++ }
  415.          print "There are $count negative numbers in the string";
  416.  
  417.  
  418.      HHHHoooowwww ddddoooo IIII ccccaaaappppiiiittttaaaalllliiiizzzzeeee aaaallllllll tttthhhheeee wwwwoooorrrrddddssss oooonnnn oooonnnneeee lllliiiinnnneeee????
  419.  
  420.      To make the first letter of each word upper case:
  421.  
  422.              $line =~ s/\b(\w)/\U$1/g;
  423.  
  424.      This has the strange effect of turning "don't do it" into "Don'T Do It".
  425.      Sometimes you might want this, instead (Suggested by Brian Foy
  426.      <comdog@computerdog.com>):
  427.  
  428.          $string =~ s/ (
  429.                       (^\w)    #at the beginning of the line
  430.                         |      # or
  431.                       (\s\w)   #preceded by whitespace
  432.                         )
  433.                      /\U$1/xg;
  434.          $string =~ /([\w']+)/\u\L$1/g;
  435.  
  436.      To make the whole line upper case:
  437.  
  438.              $line = uc($line);
  439.  
  440.      To force each word to be lower case, with the first letter upper case:
  441.  
  442.              $line =~ s/(\w+)/\u\L$1/g;
  443.  
  444.  
  445.      HHHHoooowwww ccccaaaannnn IIII sssspppplllliiiitttt aaaa [[[[cccchhhhaaaarrrraaaacccctttteeeerrrr]]]] ddddeeeelllliiiimmmmiiiitttteeeedddd ssssttttrrrriiiinnnngggg eeeexxxxcccceeeepppptttt wwwwhhhheeeennnn iiiinnnnssssiiiiddddeeee
  446.      [[[[cccchhhhaaaarrrraaaacccctttteeeerrrr]]]]???? ((((CCCCoooommmmmmmmaaaa----sssseeeeppppaaaarrrraaaatttteeeedddd ffffiiiilllleeeessss))))
  447.  
  448.      Take the example case of trying to split a string that is comma-separated
  449.      into its different fields.  (We'll pretend you said comma-separated, not
  450.      comma-delimited, which is different and almost never what you mean.) You
  451.      can't use split(/,/) because you shouldn't split if the comma is inside
  452.      quotes.  For example, take a data line like this:
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.                                                                         PPPPaaaaggggeeee 7777
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  467.  
  468.  
  469.  
  470.          SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"
  471.  
  472.      Due to the restriction of the quotes, this is a fairly complex problem.
  473.      Thankfully, we have Jeffrey Friedl, author of a highly recommended book
  474.      on regular expressions, to handle these for us.  He suggests (assuming
  475.      your string is contained in $text):
  476.  
  477.           @new = ();
  478.           push(@new, $+) while $text =~ m{
  479.               "([^\"\\]*(?:\\.[^\"\\]*)*)",?  # groups the phrase inside the quotes
  480.             | ([^,]+),?
  481.             | ,
  482.           }gx;
  483.           push(@new, undef) if substr($text,-1,1) eq ',';
  484.  
  485.      If you want to represent quotation marks inside a quotation-mark-
  486.      delimited field, escape them with backslashes (eg, "like \"this\"".
  487.      Unescaping them is a task addressed earlier in this section.
  488.  
  489.      Alternatively, the Text::ParseWords module (part of the standard perl
  490.      distribution) lets you say:
  491.  
  492.          use Text::ParseWords;
  493.          @new = quotewords(",", 0, $text);
  494.  
  495.  
  496.      HHHHoooowwww ddddoooo IIII ssssttttrrrriiiipppp bbbbllllaaaannnnkkkk ssssppppaaaacccceeee ffffrrrroooommmm tttthhhheeee bbbbeeeeggggiiiinnnnnnnniiiinnnngggg////eeeennnndddd ooooffff aaaa ssssttttrrrriiiinnnngggg????
  497.  
  498.      The simplest approach, albeit not the fastest, is probably like this:
  499.  
  500.          $string =~ s/^\s*(.*?)\s*$/$1/;
  501.  
  502.      It would be faster to do this in two steps:
  503.  
  504.          $string =~ s/^\s+//;
  505.          $string =~ s/\s+$//;
  506.  
  507.      Or more nicely written as:
  508.  
  509.          for ($string) {
  510.              s/^\s+//;
  511.              s/\s+$//;
  512.          }
  513.  
  514.  
  515.      HHHHoooowwww ddddoooo IIII eeeexxxxttttrrrraaaacccctttt sssseeeelllleeeecccctttteeeedddd ccccoooolllluuuummmmnnnnssss ffffrrrroooommmm aaaa ssssttttrrrriiiinnnngggg????
  516.  
  517.      Use _s_u_b_s_t_r() or _u_n_p_a_c_k(), both documented in the _p_e_r_l_f_u_n_c manpage.
  518.  
  519.  
  520.  
  521.  
  522.  
  523.  
  524.  
  525.                                                                         PPPPaaaaggggeeee 8888
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  533.  
  534.  
  535.  
  536.      HHHHoooowwww ddddoooo IIII ffffiiiinnnndddd tttthhhheeee ssssoooouuuunnnnddddeeeexxxx vvvvaaaalllluuuueeee ooooffff aaaa ssssttttrrrriiiinnnngggg????
  537.  
  538.      Use the standard Text::Soundex module distributed with perl.
  539.  
  540.      HHHHoooowwww ccccaaaannnn IIII eeeexxxxppppaaaannnndddd vvvvaaaarrrriiiiaaaabbbblllleeeessss iiiinnnn tttteeeexxxxtttt ssssttttrrrriiiinnnnggggssss????
  541.  
  542.      Let's assume that you have a string like:
  543.  
  544.          $text = 'this has a $foo in it and a $bar';
  545.          $text =~ s/\$(\w+)/${$1}/g;
  546.  
  547.      Before version 5 of perl, this had to be done with a double-eval
  548.      substitution:
  549.  
  550.          $text =~ s/(\$\w+)/$1/eeg;
  551.  
  552.      Which is bizarre enough that you'll probably actually need an EEG
  553.      afterwards. :-)
  554.  
  555.      See also "How do I expand function calls in a string?" in this section of
  556.      the FAQ.
  557.  
  558.      WWWWhhhhaaaatttt''''ssss wwwwrrrroooonnnngggg wwwwiiiitttthhhh aaaallllwwwwaaaayyyyssss qqqquuuuoooottttiiiinnnngggg """"$$$$vvvvaaaarrrrssss""""????
  559.  
  560.      The problem is that those double-quotes force stringification, coercing
  561.      numbers and references into strings, even when you don't want them to be.
  562.  
  563.      If you get used to writing odd things like these:
  564.  
  565.          print "$var";       # BAD
  566.          $new = "$old";      # BAD
  567.          somefunc("$var");   # BAD
  568.  
  569.      You'll be in trouble.  Those should (in 99.8% of the cases) be the
  570.      simpler and more direct:
  571.  
  572.          print $var;
  573.          $new = $old;
  574.          somefunc($var);
  575.  
  576.      Otherwise, besides slowing you down, you're going to break code when the
  577.      thing in the scalar is actually neither a string nor a number, but a
  578.      reference:
  579.  
  580.          func(\@array);
  581.          sub func {
  582.              my $aref = shift;
  583.              my $oref = "$aref";  # WRONG
  584.          }
  585.  
  586.      You can also get into subtle problems on those few operations in Perl
  587.      that actually do care about the difference between a string and a number,
  588.  
  589.  
  590.  
  591.                                                                         PPPPaaaaggggeeee 9999
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  599.  
  600.  
  601.  
  602.      such as the magical ++ autoincrement operator or the _s_y_s_c_a_l_l() function.
  603.  
  604.      WWWWhhhhyyyy ddddoooonnnn''''tttt mmmmyyyy <<<<<<<<HHHHEEEERRRREEEE ddddooooccccuuuummmmeeeennnnttttssss wwwwoooorrrrkkkk????
  605.  
  606.      Check for these three things:
  607.  
  608.      1. There must be no space after the << part.
  609.  
  610.      2. There (probably) should be a semicolon at the end.
  611.  
  612.      3. You can't (easily) have any space in front of the tag.
  613.  
  614. DDDDaaaattttaaaa:::: AAAArrrrrrrraaaayyyyssss
  615.      WWWWhhhhaaaatttt iiiissss tttthhhheeee ddddiiiiffffffffeeeerrrreeeennnncccceeee bbbbeeeettttwwwweeeeeeeennnn $$$$aaaarrrrrrrraaaayyyy[1] and @array[1]?
  616.  
  617.      The former is a scalar value, the latter an array slice, which makes it a
  618.      list with one (scalar) value.  You should use $ when you want a scalar
  619.      value (most of the time) and @ when you want a list with one scalar value
  620.      in it (very, very rarely; nearly never, in fact).
  621.  
  622.      Sometimes it doesn't make a difference, but sometimes it does.  For
  623.      example, compare:
  624.  
  625.          $good[0] = `some program that outputs several lines`;
  626.  
  627.      with
  628.  
  629.          @bad[0]  = `same program that outputs several lines`;
  630.  
  631.      The ----wwww flag will warn you about these matters.
  632.  
  633.      HHHHoooowwww ccccaaaannnn IIII eeeexxxxttttrrrraaaacccctttt jjjjuuuusssstttt tttthhhheeee uuuunnnniiiiqqqquuuueeee eeeelllleeeemmmmeeeennnnttttssss ooooffff aaaannnn aaaarrrrrrrraaaayyyy????
  634.  
  635.      There are several possible ways, depending on whether the array is
  636.      ordered and whether you wish to preserve the ordering.
  637.  
  638.      a) If @in is sorted, and you want @out to be sorted:
  639.  
  640.              $prev = 'nonesuch';
  641.              @out = grep($_ ne $prev && ($prev = $_), @in);
  642.  
  643.          This is nice in that it doesn't use much extra memory, simulating
  644.          _u_n_i_q(1)'s behavior of removing only adjacent duplicates.
  645.  
  646.      b) If you don't know whether @in is sorted:
  647.  
  648.              undef %saw;
  649.              @out = grep(!$saw{$_}++, @in);
  650.  
  651.  
  652.  
  653.  
  654.  
  655.  
  656.  
  657.                                                                        PPPPaaaaggggeeee 11110000
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  665.  
  666.  
  667.  
  668.      c) Like (b), but @in contains only small integers:
  669.  
  670.              @out = grep(!$saw[$_]++, @in);
  671.  
  672.  
  673.      d) A way to do (b) without any loops or greps:
  674.  
  675.              undef %saw;
  676.              @saw{@in} = ();
  677.              @out = sort keys %saw;  # remove sort if undesired
  678.  
  679.  
  680.      e) Like (d), but @in contains only small positive integers:
  681.  
  682.              undef @ary;
  683.              @ary[@in] = @in;
  684.              @out = @ary;
  685.  
  686.  
  687.      HHHHoooowwww ccccaaaannnn IIII tttteeeellllllll wwwwhhhheeeetttthhhheeeerrrr aaaannnn aaaarrrrrrrraaaayyyy ccccoooonnnnttttaaaaiiiinnnnssss aaaa cccceeeerrrrttttaaaaiiiinnnn eeeelllleeeemmmmeeeennnntttt????
  688.  
  689.      There are several ways to approach this.  If you are going to make this
  690.      query many times and the values are arbitrary strings, the fastest way is
  691.      probably to invert the original array and keep an associative array lying
  692.      about whose keys are the first array's values.
  693.  
  694.          @blues = qw/azure cerulean teal turquoise lapis-lazuli/;
  695.          undef %is_blue;
  696.          for (@blues) { $is_blue{$_} = 1 }
  697.  
  698.      Now you can check whether $is_blue{$some_color}.  It might have been a
  699.      good idea to keep the blues all in a hash in the first place.
  700.  
  701.      If the values are all small integers, you could use a simple indexed
  702.      array.  This kind of an array will take up less space:
  703.  
  704.          @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
  705.          undef @is_tiny_prime;
  706.          for (@primes) { $is_tiny_prime[$_] = 1; }
  707.  
  708.      Now you check whether $is_tiny_prime[$some_number].
  709.  
  710.      If the values in question are integers instead of strings, you can save
  711.      quite a lot of space by using bit strings instead:
  712.  
  713.          @articles = ( 1..10, 150..2000, 2017 );
  714.          undef $read;
  715.          grep (vec($read,$_,1) = 1, @articles);
  716.  
  717.      Now check whether vec($read,$n,1) is true for some $n.
  718.  
  719.  
  720.  
  721.  
  722.  
  723.                                                                        PPPPaaaaggggeeee 11111111
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  731.  
  732.  
  733.  
  734.      Please do not use
  735.  
  736.          $is_there = grep $_ eq $whatever, @array;
  737.  
  738.      or worse yet
  739.  
  740.          $is_there = grep /$whatever/, @array;
  741.  
  742.      These are slow (checks every element even if the first matches),
  743.      inefficient (same reason), and potentially buggy (what if there are
  744.      regexp characters in $whatever?).
  745.  
  746.      HHHHoooowwww ddddoooo IIII ccccoooommmmppppuuuutttteeee tttthhhheeee ddddiiiiffffffffeeeerrrreeeennnncccceeee ooooffff ttttwwwwoooo aaaarrrrrrrraaaayyyyssss????  HHHHoooowwww ddddoooo IIII ccccoooommmmppppuuuutttteeee tttthhhheeee
  747.      iiiinnnntttteeeerrrrsssseeeeccccttttiiiioooonnnn ooooffff ttttwwwwoooo aaaarrrrrrrraaaayyyyssss????
  748.  
  749.      Use a hash.  Here's code to do both and more.  It assumes that each
  750.      element is unique in a given array:
  751.  
  752.          @union = @intersection = @difference = ();
  753.          %count = ();
  754.          foreach $element (@array1, @array2) { $count{$element}++ }
  755.          foreach $element (keys %count) {
  756.              push @union, $element;
  757.              push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
  758.          }
  759.  
  760.  
  761.      HHHHoooowwww ddddoooo IIII ffffiiiinnnndddd tttthhhheeee ffffiiiirrrrsssstttt aaaarrrrrrrraaaayyyy eeeelllleeeemmmmeeeennnntttt ffffoooorrrr wwwwhhhhiiiicccchhhh aaaa ccccoooonnnnddddiiiittttiiiioooonnnn iiiissss ttttrrrruuuueeee????
  762.  
  763.      You can use this if you care about the index:
  764.  
  765.          for ($i=0; $i < @array; $i++) {
  766.              if ($array[$i] eq "Waldo") {
  767.                  $found_index = $i;
  768.                  last;
  769.              }
  770.          }
  771.  
  772.      Now $found_index has what you want.
  773.  
  774.      HHHHoooowwww ddddoooo IIII hhhhaaaannnnddddlllleeee lllliiiinnnnkkkkeeeedddd lllliiiissssttttssss????
  775.  
  776.      In general, you usually don't need a linked list in Perl, since with
  777.      regular arrays, you can push and pop or shift and unshift at either end,
  778.      or you can use splice to add and/or remove arbitrary number of elements
  779.      at arbitrary points.
  780.  
  781.      If you really, really wanted, you could use structures as described in
  782.      the _p_e_r_l_d_s_c manpage or the _p_e_r_l_t_o_o_t manpage and do just what the
  783.      algorithm book tells you to do.
  784.  
  785.  
  786.  
  787.  
  788.  
  789.                                                                        PPPPaaaaggggeeee 11112222
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  797.  
  798.  
  799.  
  800.      HHHHoooowwww ddddoooo IIII hhhhaaaannnnddddlllleeee cccciiiirrrrccccuuuullllaaaarrrr lllliiiissssttttssss????
  801.  
  802.      Circular lists could be handled in the traditional fashion with linked
  803.      lists, or you could just do something like this with an array:
  804.  
  805.          unshift(@array, pop(@array));  # the last shall be first
  806.          push(@array, shift(@array));   # and vice versa
  807.  
  808.  
  809.      HHHHoooowwww ddddoooo IIII sssshhhhuuuufffffffflllleeee aaaannnn aaaarrrrrrrraaaayyyy rrrraaaannnnddddoooommmmllllyyyy????
  810.  
  811.      Here's a shuffling algorithm which works its way through the list,
  812.      randomly picking another element to swap the current element with:
  813.  
  814.          srand;
  815.          @new = ();
  816.          @old = 1 .. 10;  # just a demo
  817.          while (@old) {
  818.              push(@new, splice(@old, rand @old, 1));
  819.          }
  820.  
  821.      For large arrays, this avoids a lot of the reshuffling:
  822.  
  823.          srand;
  824.          @new = ();
  825.          @old = 1 .. 10000;  # just a demo
  826.          for( @old ){
  827.              my $r = rand @new+1;
  828.              push(@new,$new[$r]);
  829.              $new[$r] = $_;
  830.          }
  831.  
  832.  
  833.      HHHHoooowwww ddddoooo IIII pppprrrroooocccceeeessssssss////mmmmooooddddiiiiffffyyyy eeeeaaaacccchhhh eeeelllleeeemmmmeeeennnntttt ooooffff aaaannnn aaaarrrrrrrraaaayyyy????
  834.  
  835.      Use for/foreach:
  836.  
  837.          for (@lines) {
  838.              s/foo/bar/;
  839.              tr[a-z][A-Z];
  840.          }
  841.  
  842.      Here's another; let's compute spherical volumes:
  843.  
  844.          for (@radii) {
  845.              $_ **= 3;
  846.              $_ *= (4/3) * 3.14159;  # this will be constant folded
  847.          }
  848.  
  849.  
  850.  
  851.  
  852.  
  853.  
  854.  
  855.                                                                        PPPPaaaaggggeeee 11113333
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  863.  
  864.  
  865.  
  866.      HHHHoooowwww ddddoooo IIII sssseeeelllleeeecccctttt aaaa rrrraaaannnnddddoooommmm eeeelllleeeemmmmeeeennnntttt ffffrrrroooommmm aaaannnn aaaarrrrrrrraaaayyyy????
  867.  
  868.      Use the _r_a_n_d() function (see the rand entry in the _p_e_r_l_f_u_n_c manpage):
  869.  
  870.          srand;                      # not needed for 5.004 and later
  871.          $index   = rand @array;
  872.          $element = $array[$index];
  873.  
  874.  
  875.      HHHHoooowwww ddddoooo IIII ppppeeeerrrrmmmmuuuutttteeee NNNN eeeelllleeeemmmmeeeennnnttttssss ooooffff aaaa lllliiiisssstttt????
  876.  
  877.      Here's a little program that generates all permutations of all the words
  878.      on each line of input.  The algorithm embodied in the _p_e_r_m_u_t() function
  879.      should work on any list:
  880.  
  881.          #!/usr/bin/perl -n
  882.          # permute - tchrist@perl.com
  883.          permut([split], []);
  884.          sub permut {
  885.              my @head = @{ $_[0] };
  886.              my @tail = @{ $_[1] };
  887.              unless (@head) {
  888.                  # stop recursing when there are no elements in the head
  889.                  print "@tail\n";
  890.              } else {
  891.                  # for all elements in @head, move one from @head to @tail
  892.                  # and call permut() on the new @head and @tail
  893.                  my(@newhead,@newtail,$i);
  894.                  foreach $i (0 .. $#head) {
  895.                      @newhead = @head;
  896.                      @newtail = @tail;
  897.                      unshift(@newtail, splice(@newhead, $i, 1));
  898.                      permut([@newhead], [@newtail]);
  899.                  }
  900.              }
  901.          }
  902.  
  903.  
  904.      HHHHoooowwww ddddoooo IIII ssssoooorrrrtttt aaaannnn aaaarrrrrrrraaaayyyy bbbbyyyy ((((aaaannnnyyyytttthhhhiiiinnnngggg))))????
  905.  
  906.      Supply a comparison function to _s_o_r_t() (described in the sort entry in
  907.      the _p_e_r_l_f_u_n_c manpage):
  908.  
  909.          @list = sort { $a <=> $b } @list;
  910.  
  911.      The default sort function is cmp, string comparison, which would sort (1,
  912.      2, 10) into (1, 10, 2).  <=>, used above, is the numerical comparison
  913.      operator.
  914.  
  915.      If you have a complicated function needed to pull out the part you want
  916.      to sort on, then don't do it inside the sort function.  Pull it out
  917.      first, because the sort BLOCK can be called many times for the same
  918.  
  919.  
  920.  
  921.                                                                        PPPPaaaaggggeeee 11114444
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  929.  
  930.  
  931.  
  932.      element.  Here's an example of how to pull out the first word after the
  933.      first number on each item, and then sort those words case-insensitively.
  934.  
  935.          @idx = ();
  936.          for (@data) {
  937.              ($item) = /\d+\s*(\S+)/;
  938.              push @idx, uc($item);
  939.          }
  940.          @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];
  941.  
  942.      Which could also be written this way, using a trick that's come to be
  943.      known as the Schwartzian Transform:
  944.  
  945.          @sorted = map  { $_->[0] }
  946.                    sort { $a->[1] cmp $b->[1] }
  947.                    map  { [ $_, uc((/\d+\s*(\S+)/ )[0] ] } @data;
  948.  
  949.      If you need to sort on several fields, the following paradigm is useful.
  950.  
  951.          @sorted = sort { field1($a) <=> field1($b) ||
  952.                           field2($a) cmp field2($b) ||
  953.                           field3($a) cmp field3($b)
  954.                         }     @data;
  955.  
  956.      This can be conveniently combined with precalculation of keys as given
  957.      above.
  958.  
  959.      See http://www.perl.com/CPAN/doc/FMTEYEWTK/sort.html for more about this
  960.      approach.
  961.  
  962.      See also the question below on sorting hashes.
  963.  
  964.      HHHHoooowwww ddddoooo IIII mmmmaaaannnniiiippppuuuullllaaaatttteeee aaaarrrrrrrraaaayyyyssss ooooffff bbbbiiiittttssss????
  965.  
  966.      Use _p_a_c_k() and _u_n_p_a_c_k(), or else _v_e_c() and the bitwise operations.
  967.  
  968.      For example, this sets $vec to have bit N set if $ints[N] was set:
  969.  
  970.          $vec = '';
  971.          foreach(@ints) { vec($vec,$_,1) = 1 }
  972.  
  973.      And here's how, given a vector in $vec, you can get those bits into your
  974.      @ints array:
  975.  
  976.  
  977.  
  978.  
  979.  
  980.  
  981.  
  982.  
  983.  
  984.  
  985.  
  986.  
  987.                                                                        PPPPaaaaggggeeee 11115555
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  995.  
  996.  
  997.  
  998.          sub bitvec_to_list {
  999.              my $vec = shift;
  1000.              my @ints;
  1001.              # Find null-byte density then select best algorithm
  1002.              if ($vec =~ tr/\0// / length $vec > 0.95) {
  1003.                  use integer;
  1004.                  my $i;
  1005.                  # This method is faster with mostly null-bytes
  1006.                  while($vec =~ /[^\0]/g ) {
  1007.                      $i = -9 + 8 * pos $vec;
  1008.                      push @ints, $i if vec($vec, ++$i, 1);
  1009.                      push @ints, $i if vec($vec, ++$i, 1);
  1010.                      push @ints, $i if vec($vec, ++$i, 1);
  1011.                      push @ints, $i if vec($vec, ++$i, 1);
  1012.                      push @ints, $i if vec($vec, ++$i, 1);
  1013.                      push @ints, $i if vec($vec, ++$i, 1);
  1014.                      push @ints, $i if vec($vec, ++$i, 1);
  1015.                      push @ints, $i if vec($vec, ++$i, 1);
  1016.                  }
  1017.              } else {
  1018.                  # This method is a fast general algorithm
  1019.                  use integer;
  1020.                  my $bits = unpack "b*", $vec;
  1021.                  push @ints, 0 if $bits =~ s/^(\d)// && $1;
  1022.                  push @ints, pos $bits while($bits =~ /1/g);
  1023.              }
  1024.              return \@ints;
  1025.          }
  1026.  
  1027.      This method gets faster the more sparse the bit vector is.  (Courtesy of
  1028.      Tim Bunce and Winfried Koenig.)
  1029.  
  1030.      WWWWhhhhyyyy ddddooooeeeessss _d_e_f_i_n_e_d() return true on empty arrays and hashes?
  1031.  
  1032.      See the defined entry in the _p_e_r_l_f_u_n_c manpage in the 5.004 release or
  1033.      later of Perl.
  1034.  
  1035. DDDDaaaattttaaaa:::: HHHHaaaasssshhhheeeessss ((((AAAAssssssssoooocccciiiiaaaattttiiiivvvveeee AAAArrrrrrrraaaayyyyssss))))
  1036.      HHHHoooowwww ddddoooo IIII pppprrrroooocccceeeessssssss aaaannnn eeeennnnttttiiiirrrreeee hhhhaaaasssshhhh????
  1037.  
  1038.      Use the _e_a_c_h() function (see the each entry in the _p_e_r_l_f_u_n_c manpage) if
  1039.      you don't care whether it's sorted:
  1040.  
  1041.          while (($key,$value) = each %hash) {
  1042.              print "$key = $value\n";
  1043.          }
  1044.  
  1045.      If you want it sorted, you'll have to use _f_o_r_e_a_c_h() on the result of
  1046.      sorting the keys as shown in an earlier question.
  1047.  
  1048.  
  1049.  
  1050.  
  1051.  
  1052.  
  1053.                                                                        PPPPaaaaggggeeee 11116666
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1061.  
  1062.  
  1063.  
  1064.      WWWWhhhhaaaatttt hhhhaaaappppppppeeeennnnssss iiiiffff IIII aaaadddddddd oooorrrr rrrreeeemmmmoooovvvveeee kkkkeeeeyyyyssss ffffrrrroooommmm aaaa hhhhaaaasssshhhh wwwwhhhhiiiilllleeee iiiitttteeeerrrraaaattttiiiinnnngggg oooovvvveeeerrrr iiiitttt????
  1065.  
  1066.      Don't do that.
  1067.  
  1068.      HHHHoooowwww ddddoooo IIII llllooooooookkkk uuuupppp aaaa hhhhaaaasssshhhh eeeelllleeeemmmmeeeennnntttt bbbbyyyy vvvvaaaalllluuuueeee????
  1069.  
  1070.      Create a reverse hash:
  1071.  
  1072.          %by_value = reverse %by_key;
  1073.          $key = $by_value{$value};
  1074.  
  1075.      That's not particularly efficient.  It would be more space-efficient to
  1076.      use:
  1077.  
  1078.          while (($key, $value) = each %by_key) {
  1079.              $by_value{$value} = $key;
  1080.          }
  1081.  
  1082.      If your hash could have repeated values, the methods above will only find
  1083.      one of the associated keys.   This may or may not worry you.
  1084.  
  1085.      HHHHoooowwww ccccaaaannnn IIII kkkknnnnoooowwww hhhhoooowwww mmmmaaaannnnyyyy eeeennnnttttrrrriiiieeeessss aaaarrrreeee iiiinnnn aaaa hhhhaaaasssshhhh????
  1086.  
  1087.      If you mean how many keys, then all you have to do is take the scalar
  1088.      sense of the _k_e_y_s() function:
  1089.  
  1090.          $num_keys = scalar keys %hash;
  1091.  
  1092.      In void context it just resets the iterator, which is faster for tied
  1093.      hashes.
  1094.  
  1095.      HHHHoooowwww ddddoooo IIII ssssoooorrrrtttt aaaa hhhhaaaasssshhhh ((((ooooppppttttiiiioooonnnnaaaallllllllyyyy bbbbyyyy vvvvaaaalllluuuueeee iiiinnnnsssstttteeeeaaaadddd ooooffff kkkkeeeeyyyy))))????
  1096.  
  1097.      Internally, hashes are stored in a way that prevents you from imposing an
  1098.      order on key-value pairs.  Instead, you have to sort a list of the keys
  1099.      or values:
  1100.  
  1101.          @keys = sort keys %hash;    # sorted by key
  1102.          @keys = sort {
  1103.                          $hash{$a} cmp $hash{$b}
  1104.                  } keys %hash;       # and by value
  1105.  
  1106.      Here we'll do a reverse numeric sort by value, and if two keys are
  1107.      identical, sort by length of key, and if that fails, by straight ASCII
  1108.      comparison of the keys (well, possibly modified by your locale -- see the
  1109.      _p_e_r_l_l_o_c_a_l_e manpage).
  1110.  
  1111.  
  1112.  
  1113.  
  1114.  
  1115.  
  1116.  
  1117.  
  1118.  
  1119.                                                                        PPPPaaaaggggeeee 11117777
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1127.  
  1128.  
  1129.  
  1130.          @keys = sort {
  1131.                      $hash{$b} <=> $hash{$a}
  1132.                                ||
  1133.                      length($b) <=> length($a)
  1134.                                ||
  1135.                            $a cmp $b
  1136.          } keys %hash;
  1137.  
  1138.  
  1139.      HHHHoooowwww ccccaaaannnn IIII aaaallllwwwwaaaayyyyssss kkkkeeeeeeeepppp mmmmyyyy hhhhaaaasssshhhh ssssoooorrrrtttteeeedddd????
  1140.  
  1141.      You can look into using the DB_File module and _t_i_e() using the $DB_BTREE
  1142.      hash bindings as documented in the section on _I_n _M_e_m_o_r_y _D_a_t_a_b_a_s_e_s in the
  1143.      _D_B__F_i_l_e manpage.
  1144.  
  1145.      WWWWhhhhaaaatttt''''ssss tttthhhheeee ddddiiiiffffffffeeeerrrreeeennnncccceeee bbbbeeeettttwwwweeeeeeeennnn """"ddddeeeelllleeeetttteeee"""" aaaannnndddd """"uuuunnnnddddeeeeffff"""" wwwwiiiitttthhhh hhhhaaaasssshhhheeeessss????
  1146.  
  1147.      Hashes are pairs of scalars: the first is the key, the second is the
  1148.      value.  The key will be coerced to a string, although the value can be
  1149.      any kind of scalar: string, number, or reference.  If a key $key is
  1150.      present in the array, exists($key) will return true.  The value for a
  1151.      given key can be undef, in which case $array{$key} will be undef while
  1152.      $exists{$key} will return true.  This corresponds to ($key, undef) being
  1153.      in the hash.
  1154.  
  1155.      Pictures help...  here's the %ary table:
  1156.  
  1157.                keys  values
  1158.              +------+------+
  1159.              |  a   |  3   |
  1160.              |  x   |  7   |
  1161.              |  d   |  0   |
  1162.              |  e   |  2   |
  1163.              +------+------+
  1164.  
  1165.      And these conditions hold
  1166.  
  1167.              $ary{'a'}                       is true
  1168.              $ary{'d'}                       is false
  1169.              defined $ary{'d'}               is true
  1170.              defined $ary{'a'}               is true
  1171.              exists $ary{'a'}                is true (perl5 only)
  1172.              grep ($_ eq 'a', keys %ary)     is true
  1173.  
  1174.      If you now say
  1175.  
  1176.              undef $ary{'a'}
  1177.  
  1178.      your table now reads:
  1179.  
  1180.  
  1181.  
  1182.  
  1183.  
  1184.  
  1185.                                                                        PPPPaaaaggggeeee 11118888
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1193.  
  1194.  
  1195.  
  1196.                keys  values
  1197.              +------+------+
  1198.              |  a   | undef|
  1199.              |  x   |  7   |
  1200.              |  d   |  0   |
  1201.              |  e   |  2   |
  1202.              +------+------+
  1203.  
  1204.      and these conditions now hold; changes in caps:
  1205.  
  1206.              $ary{'a'}                       is FALSE
  1207.              $ary{'d'}                       is false
  1208.              defined $ary{'d'}               is true
  1209.              defined $ary{'a'}               is FALSE
  1210.              exists $ary{'a'}                is true (perl5 only)
  1211.              grep ($_ eq 'a', keys %ary)     is true
  1212.  
  1213.      Notice the last two: you have an undef value, but a defined key!
  1214.  
  1215.      Now, consider this:
  1216.  
  1217.              delete $ary{'a'}
  1218.  
  1219.      your table now reads:
  1220.  
  1221.                keys  values
  1222.              +------+------+
  1223.              |  x   |  7   |
  1224.              |  d   |  0   |
  1225.              |  e   |  2   |
  1226.              +------+------+
  1227.  
  1228.      and these conditions now hold; changes in caps:
  1229.  
  1230.              $ary{'a'}                       is false
  1231.              $ary{'d'}                       is false
  1232.              defined $ary{'d'}               is true
  1233.              defined $ary{'a'}               is false
  1234.              exists $ary{'a'}                is FALSE (perl5 only)
  1235.              grep ($_ eq 'a', keys %ary)     is FALSE
  1236.  
  1237.      See, the whole entry is gone!
  1238.  
  1239.      WWWWhhhhyyyy ddddoooonnnn''''tttt mmmmyyyy ttttiiiieeeedddd hhhhaaaasssshhhheeeessss mmmmaaaakkkkeeee tttthhhheeee ddddeeeeffffiiiinnnneeeedddd////eeeexxxxiiiissssttttssss ddddiiiissssttttiiiinnnnccccttttiiiioooonnnn????
  1240.  
  1241.      They may or may not implement the _E_X_I_S_T_S() and _D_E_F_I_N_E_D() methods
  1242.      differently.  For example, there isn't the concept of undef with hashes
  1243.      that are tied to DBM* files. This means the true/false tables above will
  1244.      give different results when used on such a hash.  It also means that
  1245.      exists and defined do the same thing with a DBM* file, and what they end
  1246.      up doing is not what they do with ordinary hashes.
  1247.  
  1248.  
  1249.  
  1250.  
  1251.                                                                        PPPPaaaaggggeeee 11119999
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1259.  
  1260.  
  1261.  
  1262.      HHHHoooowwww ddddoooo IIII rrrreeeesssseeeetttt aaaannnn _e_a_c_h() operation part-way through?
  1263.  
  1264.      Using keys %hash in a scalar context returns the number of keys in the
  1265.      hash _a_n_d resets the iterator associated with the hash.  You may need to
  1266.      do this if you use last to exit a loop early so that when you re-enter
  1267.      it, the hash iterator has been reset.
  1268.  
  1269.      HHHHoooowwww ccccaaaannnn IIII ggggeeeetttt tttthhhheeee uuuunnnniiiiqqqquuuueeee kkkkeeeeyyyyssss ffffrrrroooommmm ttttwwwwoooo hhhhaaaasssshhhheeeessss????
  1270.  
  1271.      First you extract the keys from the hashes into arrays, and then solve
  1272.      the uniquifying the array problem described above.  For example:
  1273.  
  1274.          %seen = ();
  1275.          for $element (keys(%foo), keys(%bar)) {
  1276.              $seen{$element}++;
  1277.          }
  1278.          @uniq = keys %seen;
  1279.  
  1280.      Or more succinctly:
  1281.  
  1282.          @uniq = keys %{{%foo,%bar}};
  1283.  
  1284.      Or if you really want to save space:
  1285.  
  1286.          %seen = ();
  1287.          while (defined ($key = each %foo)) {
  1288.              $seen{$key}++;
  1289.          }
  1290.          while (defined ($key = each %bar)) {
  1291.              $seen{$key}++;
  1292.          }
  1293.          @uniq = keys %seen;
  1294.  
  1295.  
  1296.      HHHHoooowwww ccccaaaannnn IIII ssssttttoooorrrreeee aaaa mmmmuuuullllttttiiiiddddiiiimmmmeeeennnnssssiiiioooonnnnaaaallll aaaarrrrrrrraaaayyyy iiiinnnn aaaa DDDDBBBBMMMM ffffiiiilllleeee????
  1297.  
  1298.      Either stringify the structure yourself (no fun), or else get the MLDBM
  1299.      (which uses Data::Dumper) module from CPAN and layer it on top of either
  1300.      DB_File or GDBM_File.
  1301.  
  1302.      HHHHoooowwww ccccaaaannnn IIII mmmmaaaakkkkeeee mmmmyyyy hhhhaaaasssshhhh rrrreeeemmmmeeeemmmmbbbbeeeerrrr tttthhhheeee oooorrrrddddeeeerrrr IIII ppppuuuutttt eeeelllleeeemmmmeeeennnnttttssss iiiinnnnttttoooo iiiitttt????
  1303.  
  1304.      Use the Tie::IxHash from CPAN.
  1305.  
  1306.          use Tie::IxHash;
  1307.          tie(%myhash, Tie::IxHash);
  1308.          for ($i=0; $i<20; $i++) {
  1309.              $myhash{$i} = 2*$i;
  1310.          }
  1311.          @keys = keys %myhash;
  1312.          # @keys = (0,1,2,3,...)
  1313.  
  1314.  
  1315.  
  1316.  
  1317.                                                                        PPPPaaaaggggeeee 22220000
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1325.  
  1326.  
  1327.  
  1328.      WWWWhhhhyyyy ddddooooeeeessss ppppaaaassssssssiiiinnnngggg aaaa ssssuuuubbbbrrrroooouuuuttttiiiinnnneeee aaaannnn uuuunnnnddddeeeeffffiiiinnnneeeedddd eeeelllleeeemmmmeeeennnntttt iiiinnnn aaaa hhhhaaaasssshhhh ccccrrrreeeeaaaatttteeee iiiitttt????
  1329.  
  1330.      If you say something like:
  1331.  
  1332.          somefunc($hash{"nonesuch key here"});
  1333.  
  1334.      Then that element "autovivifies"; that is, it springs into existence
  1335.      whether you store something there or not.  That's because functions get
  1336.      scalars passed in by reference.  If _s_o_m_e_f_u_n_c() modifies $_[0], it has to
  1337.      be ready to write it back into the caller's version.
  1338.  
  1339.      This has been fixed as of perl5.004.
  1340.  
  1341.      Normally, merely accessing a key's value for a nonexistent key does _n_o_t
  1342.      cause that key to be forever there.  This is different than awk's
  1343.      behavior.
  1344.  
  1345.      HHHHoooowwww ccccaaaannnn IIII mmmmaaaakkkkeeee tttthhhheeee PPPPeeeerrrrllll eeeeqqqquuuuiiiivvvvaaaalllleeeennnntttt ooooffff aaaa CCCC ssssttttrrrruuuuccccttttuuuurrrreeee////CCCC++++++++ ccccllllaaaassssssss////hhhhaaaasssshhhh oooorrrr
  1346.      aaaarrrrrrrraaaayyyy ooooffff hhhhaaaasssshhhheeeessss oooorrrr aaaarrrrrrrraaaayyyyssss????
  1347.  
  1348.      Use references (documented in the _p_e_r_l_r_e_f manpage).  Examples of complex
  1349.      data structures are given in the _p_e_r_l_d_s_c manpage and the _p_e_r_l_l_o_l manpage.
  1350.      Examples of structures and object-oriented classes are in the _p_e_r_l_t_o_o_t
  1351.      manpage.
  1352.  
  1353.      HHHHoooowwww ccccaaaannnn IIII uuuusssseeee aaaa rrrreeeeffffeeeerrrreeeennnncccceeee aaaassss aaaa hhhhaaaasssshhhh kkkkeeeeyyyy????
  1354.  
  1355.      You can't do this directly, but you could use the standard Tie::Refhash
  1356.      module distributed with perl.
  1357.  
  1358. DDDDaaaattttaaaa:::: MMMMiiiisssscccc
  1359.      HHHHoooowwww ddddoooo IIII hhhhaaaannnnddddlllleeee bbbbiiiinnnnaaaarrrryyyy ddddaaaattttaaaa ccccoooorrrrrrrreeeeccccttttllllyyyy????
  1360.  
  1361.      Perl is binary clean, so this shouldn't be a problem.  For example, this
  1362.      works fine (assuming the files are found):
  1363.  
  1364.          if (`cat /vmunix` =~ /gzip/) {
  1365.              print "Your kernel is GNU-zip enabled!\n";
  1366.          }
  1367.  
  1368.      On some systems, however, you have to play tedious games with "text"
  1369.      versus "binary" files.  See the section on _b_i_n_m_o_d_e in the _p_e_r_l_f_u_n_c
  1370.      manpage.
  1371.  
  1372.      If you're concerned about 8-bit ASCII data, then see the _p_e_r_l_l_o_c_a_l_e
  1373.      manpage.
  1374.  
  1375.      If you want to deal with multibyte characters, however, there are some
  1376.      gotchas.  See the section on Regular Expressions.
  1377.  
  1378.  
  1379.  
  1380.  
  1381.  
  1382.  
  1383.                                                                        PPPPaaaaggggeeee 22221111
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1391.  
  1392.  
  1393.  
  1394.      HHHHoooowwww ddddoooo IIII ddddeeeetttteeeerrrrmmmmiiiinnnneeee wwwwhhhheeeetttthhhheeeerrrr aaaa ssssccccaaaallllaaaarrrr iiiissss aaaa nnnnuuuummmmbbbbeeeerrrr////wwwwhhhhoooolllleeee////iiiinnnntttteeeeggggeeeerrrr////ffffllllooooaaaatttt????
  1395.  
  1396.      Assuming that you don't care about IEEE notations like "NaN" or
  1397.      "Infinity", you probably just want to use a regular expression.
  1398.  
  1399.         warn "has nondigits"        if     /\D/;
  1400.         warn "not a whole number"   unless /^\d+$/;
  1401.         warn "not an integer"       unless /^-?\d+$/;  # reject +3
  1402.         warn "not an integer"       unless /^[+-]?\d+$/;
  1403.         warn "not a decimal number" unless /^-?\d+\.?\d*$/;  # rejects .2
  1404.         warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
  1405.         warn "not a C float"
  1406.             unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
  1407.  
  1408.      Or you could check out http://www.perl.com/CPAN/modules/by-
  1409.      module/String/String-Scanf-1.1.tar.gz instead.  The POSIX module (part of
  1410.      the standard Perl distribution) provides the strtol and strtod for
  1411.      converting strings to double and longs, respectively.
  1412.  
  1413.      HHHHoooowwww ddddoooo IIII kkkkeeeeeeeepppp ppppeeeerrrrssssiiiisssstttteeeennnntttt ddddaaaattttaaaa aaaaccccrrrroooossssssss pppprrrrooooggggrrrraaaammmm ccccaaaallllllllssss????
  1414.  
  1415.      For some specific applications, you can use one of the DBM modules.  See
  1416.      the _A_n_y_D_B_M__F_i_l_e manpage.  More generically, you should consult the
  1417.      FreezeThaw, Storable, or Class::Eroot modules from CPAN.
  1418.  
  1419.      HHHHoooowwww ddddoooo IIII pppprrrriiiinnnntttt oooouuuutttt oooorrrr ccccooooppppyyyy aaaa rrrreeeeccccuuuurrrrssssiiiivvvveeee ddddaaaattttaaaa ssssttttrrrruuuuccccttttuuuurrrreeee????
  1420.  
  1421.      The Data::Dumper module on CPAN is nice for printing out data structures,
  1422.      and FreezeThaw for copying them.  For example:
  1423.  
  1424.          use FreezeThaw qw(freeze thaw);
  1425.          $new = thaw freeze $old;
  1426.  
  1427.      Where $old can be (a reference to) any kind of data structure you'd like.
  1428.      It will be deeply copied.
  1429.  
  1430.      HHHHoooowwww ddddoooo IIII ddddeeeeffffiiiinnnneeee mmmmeeeetttthhhhooooddddssss ffffoooorrrr eeeevvvveeeerrrryyyy ccccllllaaaassssssss////oooobbbbjjjjeeeecccctttt????
  1431.  
  1432.      Use the UNIVERSAL class (see the _U_N_I_V_E_R_S_A_L manpage).
  1433.  
  1434.      HHHHoooowwww ddddoooo IIII vvvveeeerrrriiiiffffyyyy aaaa ccccrrrreeeeddddiiiitttt ccccaaaarrrrdddd cccchhhheeeecccckkkkssssuuuummmm????
  1435.  
  1436.      Get the Business::CreditCard module from CPAN.
  1437.  
  1438. AAAAUUUUTTTTHHHHOOOORRRR AAAANNNNDDDD CCCCOOOOPPPPYYYYRRRRIIIIGGGGHHHHTTTT
  1439.      Copyright (c) 1997 Tom Christiansen and Nathan Torkington.  All rights
  1440.      reserved.  See the _p_e_r_l_f_a_q manpage for distribution information.
  1441.  
  1442.  
  1443.  
  1444.  
  1445.  
  1446.  
  1447.  
  1448.  
  1449.                                                                        PPPPaaaaggggeeee 22222222
  1450.  
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456. PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1457.  
  1458.  
  1459.  
  1460.  
  1461.  
  1462.  
  1463.  
  1464.  
  1465.  
  1466.  
  1467.  
  1468.  
  1469.  
  1470.  
  1471.  
  1472.  
  1473.  
  1474.  
  1475.  
  1476.  
  1477.  
  1478.  
  1479.  
  1480.  
  1481.  
  1482.  
  1483.  
  1484.  
  1485.  
  1486.  
  1487.  
  1488.  
  1489.  
  1490.  
  1491.  
  1492.  
  1493.  
  1494.  
  1495.  
  1496.  
  1497.  
  1498.  
  1499.  
  1500.  
  1501.  
  1502.  
  1503.  
  1504.  
  1505.  
  1506.  
  1507.  
  1508.  
  1509.  
  1510.  
  1511.  
  1512.                                                                        PPPPaaaaggggeeee 22223333
  1513.  
  1514.  
  1515.  
  1516.  
  1517.  
  1518.  
  1519.